import { log } from 'util';

const fs = require('fs');
const FileUtil = {};

FileUtil.open = function (dir) {
    return new Promise(function (resolve, reject) {
        fs.readFile(dir, { encoding: "utf-8" }, (err, data) => {
            if (err) {
                throw err;
            }
            resolve(data);
        });
    })
}

FileUtil.out = function (data, path) {
    if(path==""||path.length<1){
        console.log("错误的路径");
        return ;
    }
    mkdirs(path)
    return new Promise(function (resolve, reject) { 
        fs.writeFile(path, data, 'utf8',(err) => {
            if (err) {
                console.log("生成文件[error]："+path);
                throw err
            }; 
            console.log("生成文件[success]："+path);
            resolve("o k");
        });

    })
}

function mkdirs(path){ 
    console.log(path);
       
    if(path==""||path.length<1){
        return ;
    }   
    var str = path.substring(0,path.lastIndexOf("\\"));   
    if(fs.existsSync(str)){
       return ; 
    }else{
        if(str==""||str.length<1){
            return ;
        }
        mkdirs(str)  
        console.log("创建目录："+str);           
        fs.mkdirSync(str)
    }
}

export default FileUtil;